import os
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

#  TODO 封装函数
class MouseOperation:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get("https://sahitest.com/demo/clicks.htm")
    def click(self):
        # 单击 第一种方式
        time.sleep(3)
        btn = self.driver.find_element(By.XPATH, "//form/input[3]")
        btn.click()

        # 第二种方式
        ac = ActionChains(driver=self.driver)
        # 绑定方法之后,必须调用perform方法才会执行操作
        ac.click(btn).perform()

    def context_click(self):
        # 右击
        ac = ActionChains(driver=self.driver)
        btn = self.driver.find_element(By.XPATH, "/html/body/form/input[4]")
        ac.context_click(btn).perform()

    def double_click(self):
        # 双击
        ac = ActionChains(self.driver)
        btn = self.driver.find_element(By.XPATH, "html/body/form/input[2]")
        ac.double_click(btn).perform()

    def drag_and_drop(self):
        # 拖动
        time.sleep(3)
        self.driver.get("https://sahitest.com/demo/dragDropMooTools.htm")
        ac = ActionChains(self.driver)
        source = self.driver.find_element(By.ID, "dragger")
        target = self.driver.find_element(By.XPATH, "//div[4]")
        ac.drag_and_drop(source, target).perform()

    def move_to_element(self):
        # 悬停
        self.driver.get("https://sahitest.com/demo/mouseover.htm")
        time.sleep(3)
        ac = ActionChains(self.driver)
        btn = self.driver.find_element(By.XPATH, "//div/div")
        ac.move_to_element(btn).perform()

    def click_hold(self):
        # 长按操作
        file = 'file:///' + os.path.abspath('../html') + '/mouse_hold.html'

        self.driver.get(file)
        time.sleep(1)
        btn = self.driver.find_element(By.ID, "btn1")
        ac = ActionChains(self.driver)
        ac.click_and_hold(btn).perform()
        time.sleep(5)

    def quit(self):
        time.sleep(3)
        self.driver.quit()

if __name__ == '__main__':
    mo = MouseOperation()
    # mo.click()
    # mo.context_click()
    # mo.drag_and_drop()
    # mo.move_to_element()
    mo.click_hold()
    mo.quit()